package com.example.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.example.exception.CustomException;
import com.example.mapper.AdminMapper;
import com.example.pojo.Account;
import com.example.pojo.Admin;
import com.example.pojo.LoginResponse;
import com.example.service.AdminService;
import com.example.util.JwtUtil;
import com.example.util.Md5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestHeader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl implements AdminService {
    @Resource
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 添加用户
     *
     * @param admin
     */
    @Override
    public void add(Admin admin) {
        Admin dbAdmin = adminMapper.selectByUsername(admin.getUsername());
        if (dbAdmin!=null){
            throw new CustomException("500","账号已存在");
        }
        if (StrUtil.isBlank(admin.getPassword())){//未填密码
            admin.setPassword("12345");//设置默认密码
        }

        if (StrUtil.isBlank(admin.getName())){//未填姓名
            admin.setName(admin.getUsername());//设置账号为默认姓名
        }

        if (StrUtil.isBlank(admin.getAvatar())){//未填手机号
            admin.setAvatar("https://house1205.oss-cn-shenzhen.aliyuncs.com/%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F.png");//设置默认手机号
        }
        admin.setRole("admin");//设置角色为管理员
        String md5String = Md5Util.getMD5String(admin.getPassword());//加密密码
        admin.setPassword(md5String);
        adminMapper.add(admin);
    }

    /**
     * 注册
     *
     * @param admin
     */
    @Override
    public void register(Admin admin) {
        this.add(admin);
    }



    /**
     * 根据账号查询用户
     *
     * @param username
     */
    @Override
    public Admin selectByUsername(String username) {
        Admin admin = adminMapper.selectByUsername(username);
        return admin;
    }

    /**
     * 登录
     *
     * @param account
     */
    @Override
    public LoginResponse login(Account account) {
        String username = account.getUsername();//账号
        Admin dbAdmin = adminMapper.selectByUsername(username);
        if (dbAdmin == null){
            throw new CustomException("500","账号不存在");
        }
        String password = account.getPassword();//密码
        if (!Md5Util.checkPassword(password,dbAdmin.getPassword())){
            throw new CustomException("500","用户名或密码错误");
        }
        //登录成功
        Map<String, Object> claims = new HashMap<>();
        claims.put("id",dbAdmin.getId());
        claims.put("username",username);
        claims.put("name",dbAdmin.getName());
        claims.put("role",dbAdmin.getRole());
        //登录成功后，返回token
        String token = JwtUtil.genToken(claims);

        //把token存储到redis中
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(token,token,2, TimeUnit.HOURS);//过期时间 2小时

        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setAccount(dbAdmin);
        loginResponse.setToken(token);

        return loginResponse;
    }


    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public Admin selectById(Integer id) {
        Admin admin = adminMapper.selectById(id);
        return admin;
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    /**
     * 批量删除数据
     *
     * @param ids
     */
    @Override
    public void deleteBatch(List<Integer> ids) {
        for (Integer id:ids)
            adminMapper.deleteById(id);
    }

    /**
     * 修改密码
     *
     * @param account
     */
    @Override
    public void updatePassword(Account account,@RequestHeader("Authorization") String token) {
        Integer id = account.getId();
        Admin dbAdmin = adminMapper.selectById(id);
        if (!dbAdmin.getPassword().equals(Md5Util.getMD5String(account.getPassword()))){
            throw new CustomException("500","原密码错误");
        }
        dbAdmin.setPassword(Md5Util.getMD5String(account.getNewPassword()));
        this.updateById(dbAdmin);
        //修改密码后，注销token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
    }


    /**
     * 修改用户
     *
     * @param admin
     */
    @Override
    public void updateById(Admin admin) {
        adminMapper.updateById(admin);
    }

    /**
     * 查询所有用户
     *
     * @return
     */
    @Override
    public List<Admin> selectAll(Admin admin) {
        List<Admin> list = adminMapper.selectAll(admin);
        return list;
    }

    /**
     * 分页查询
     *
     * @param pageNum  查询哪一页
     * @param pageSize 一页的大小
     * @return
     */
    @Override
    public PageInfo<Admin> selectPage(Admin admin,Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        return PageInfo.of(list);
    }
}
